package com.nantai.jiafang.nantaijiafang.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.bean.ReportInfo;
import com.nantai.jiafang.nantaijiafang.utils.Tools;
import com.nantai.jiafang.nantaijiafang.view.Public;
import com.nantai.jiafang.nantaijiafang.view.ReportView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.nantai.jiafang.nantaijiafang.activity.DataSearchActivity.daysBetween;

public class ReportActivity extends AppCompatActivity {
    private Button btn_search;
    private Context mContext;
    private ProgressDialog progressDialog;
    private ReportView mReportView;

    private TextView tv_level;
    private String level = "A";//面料等级 A，B
    private String strs_level[] = new String[]{ "A", "B"};
    private TextView tv_start_date;
    private TextView tv_end_date;
    private Calendar calendar;
    private int current_start_end_date_state = 1;
    public static String order ="DESC";
    private Button btn_read;
    private Button btn_unread;
    private Button btn_open_close;
    private LinearLayout ll_result;
    private LinearLayout ll_search_conditions;
    private TextView tv_back;
    private Spinner mSpinner;
    private String cutArea="全部";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_search_report);
        mContext = ReportActivity.this;
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        initViews();
    }

    private void initViews() {
        btn_search = (Button) findViewById(R.id.btn_search);
        mReportView = (ReportView) findViewById(R.id.report_view);
        tv_level = (TextView) findViewById(R.id.tv_level);
        tv_end_date = (TextView) findViewById(R.id.tv_end_date);
        tv_start_date = (TextView) findViewById(R.id.tv_start_date);
        btn_read = (Button) findViewById(R.id.btn_read);
        btn_unread = (Button) findViewById(R.id.btn_unread);
        ll_result = (LinearLayout) findViewById(R.id.ll_result);
        btn_open_close = (Button) findViewById(R.id.btn_open_close);
        ll_search_conditions = (LinearLayout) findViewById(R.id.ll_search_conditions);
        tv_back = (TextView) findViewById(R.id.tv_back);
        mSpinner=(Spinner)findViewById(R.id.spinner_select);
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cutArea=(String) mSpinner.getSelectedItem();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(calendar.getTime());

        tv_end_date.setText(date);
        calendar.set(calendar.DATE,calendar.get(calendar.DATE) - 15);
        date = format.format(calendar.getTime());
        tv_start_date.setText(date);
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Tools.isNetAvailuable(mContext)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date d1 = sdf.parse(tv_start_date.getText().toString());
                        Date d2 = sdf.parse(tv_end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(mContext, "开始日期要在结束日期之后");
                        } else if (daysBetween(d1, d2) <15) {
                            Tools.showToast(mContext, "日期间隔不能小于15天");
                        } else {
                            progressDialog = new ProgressDialog(mContext);
                            progressDialog.setMessage("正在获取数据，请稍候");
                            progressDialog.show();
                            getData();
                        }
                    } catch (ParseException e) {

                    }

                } else {
                    Tools.showToast(mContext, "当前网络不可用，请检查网络");
                }
            }
        });
        tv_level.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLevelDialog();
            }
        });

        tv_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                current_start_end_date_state = 1;
                DatePickerDialog dpd = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd.show();
            }
        });

        tv_end_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                current_start_end_date_state = 2;
                DatePickerDialog dpd2 = new DatePickerDialog(mContext, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
            }
        });

        btn_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Tools.isNetAvailuable(mContext)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date d1 = sdf.parse(tv_start_date.getText().toString());
                        Date d2 = sdf.parse(tv_end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(mContext, "开始日期要在结束日期之后");
                        } else if (daysBetween(d1, d2) <15) {
                            Tools.showToast(mContext, "日期间隔不能小于15天");
                        } else {
                            progressDialog = new ProgressDialog(mContext);
                            progressDialog.setMessage("正在获取数据，请稍候");
                            progressDialog.show();
                            order = "ASC";
                            getData();
                        }
                    } catch (ParseException e) {

                    }

                } else {
                    Tools.showToast(mContext, "当前网络不可用，请检查网络");
                }
            }
        });
        btn_unread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Tools.isNetAvailuable(mContext)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date d1 = sdf.parse(tv_start_date.getText().toString());
                        Date d2 = sdf.parse(tv_end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(mContext, "开始日期要在结束日期之后");
                        } else if (daysBetween(d1, d2) <15) {
                            Tools.showToast(mContext, "日期间隔不能小于15天");
                        } else {
                            progressDialog = new ProgressDialog(mContext);
                            progressDialog.setMessage("正在获取数据，请稍候");
                            progressDialog.show();
                            order = "DESC";
                            getData();
                        }
                    } catch (ParseException e) {

                    }

                } else {
                    Tools.showToast(mContext, "当前网络不可用，请检查网络");
                }
            }
        });

        btn_open_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_open_close.getText().equals("收起")) {
                    btn_open_close.setText("展开");
                    ll_search_conditions.setVisibility(View.GONE);
                    mReportView.setBig(true);
                } else {
                    btn_open_close.setText("收起");
                    ll_search_conditions.setVisibility(View.VISIBLE);
                    mReportView.setBig(false);
                }

            }
        });

        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });




    }

    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {

            if (current_start_end_date_state == 1) {
                tv_start_date.setText(myyear + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            } else {
                tv_end_date.setText(myyear + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }

        private void updateDate() {

        }
    };


    private void showLevelDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("面料等级");
        builder.setItems(strs_level, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_level.setText(strs_level[which]);
                level = strs_level[which];
            }
        });
        builder.create().show();

    }


    private void getData() {
        String urll;
        if (Public.NAME.equals("南泰")){
            urll= IConstant.URL2;
        }else{
            urll= IConstant.URL;
        }
       // http://222.188.95.94:7065/ReportHandler.ashx?rptType
       // String url=urll+"003012&txtDocNo&txtComponentInvInfo&txtBeginDate=2018-04-03&txtEndDate=2018-04-03&txtLevels=A&CutArea=老厂";
       // String url=urll+"ComponentRank&txtBeginDate=2018-04-08&txtEndDate=2018-04-23&txtLevels=A&txtOrder=DESC&CutArea=老厂";
        String url=urll+"ComponentRank&txtBeginDate="+tv_start_date.getText().toString()
                +"&txtEndDate="+tv_end_date.getText().toString()+"&txtLevels="+level+"&txtOrder="+order+"&CutArea="+getEncodeURI(cutArea);

        //url=URLEncoder.encode(url);
        System.out.println("请求的URL2：" + url);
//        RequestParams params = new RequestParams(url);
//        params.addParameter();
        //params.setSslSocketFactory(...); // 设置ssl
//        params.addBodyParameter("loginName", et_username.getText().toString());
//        params.addBodyParameter("password", et_pwd.getText().toString());

        StringRequest jsonRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("返回结果", "返回结果2: "+response );
                Gson gson = new Gson();
                try {
                    JSONObject jo = new JSONObject(response);
                    List<ReportInfo> list_fabric = gson.fromJson(jo.getString("Table"), new TypeToken<List<ReportInfo>>() {
                    }.getType());
                    System.out.println("返回结果：" + list_fabric);
                    mReportView.setmData(list_fabric);
                    ll_result.setVisibility(View.VISIBLE);
                    if("ASC".equals(order)){
                        btn_read.setTextColor(Color.RED);
                        btn_unread.setTextColor(Color.BLACK);
                    }else {
                        btn_read.setTextColor(Color.BLACK);
                        btn_unread.setTextColor(Color.RED);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                progressDialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("返回结果", "返回结果: "+error.getCause() );
                progressDialog.dismiss();
//                Tools.showToast(mContext, "请求出错，请重试");
//                ll_result.setVisibility(View.GONE);
//                //System.out.println("出错：" + ex.getCause().toString());
            }
        });
        jsonRequest.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, 1.0f));
        Volley.newRequestQueue(this).add(jsonRequest);
//        x.http().get(params, new Callback.CommonCallback<String>() {
//            @Override
//            public void onSuccess(String result) {
//                Log.e("返回结果", "返回结果: "+result );
//                Gson gson = new Gson();
//                try {
//                    JSONObject jo = new JSONObject(result);
//                    List<ReportInfo> list_fabric = gson.fromJson(jo.getString("Table"), new TypeToken<List<ReportInfo>>() {
//                    }.getType());
//                    System.out.println("返回结果：" + list_fabric);
//                    mReportView.setmData(list_fabric);
//                    ll_result.setVisibility(View.VISIBLE);
//                    if("ASC".equals(order)){
//                        btn_read.setTextColor(Color.RED);
//                        btn_unread.setTextColor(Color.BLACK);
//                    }else {
//                        btn_read.setTextColor(Color.BLACK);
//                        btn_unread.setTextColor(Color.RED);
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//                progressDialog.dismiss();
//                Tools.showToast(mContext, "请求出错，请重试");
//                ll_result.setVisibility(View.GONE);
//                //System.out.println("出错：" + ex.getCause().toString());
//
//            }
//
//            @Override
//            public void onCancelled(CancelledException cex) {
//                progressDialog.dismiss();
//                Toast.makeText(mContext, "cancelled", Toast.LENGTH_LONG).show();
//                ll_result.setVisibility(View.GONE);
//            }
//
//            @Override
//            public void onFinished() {
//                progressDialog.dismiss();
//            }
//        });
    }
    //URL编码
    private  String getEncodeURI(String url){
        return URLEncoder.encode(url);
    }

}
